package com.cosin.controller;

import com.cosin.model.vo.FileVo;
import com.cosin.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${file.upload-path}")
    private String localPathDir;

    @Autowired
    FileService fileService;
    @CrossOrigin
    @RequestMapping("/getImg")
    public ResponseEntity<Resource> getFile(@RequestParam String filePath) {
        File file = new File(localPathDir+filePath);
        Resource resource = new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.IMAGE_PNG)
                .body(resource);
    }

    @RequestMapping("/download")
    public ResponseEntity<Resource> getBackgroundImage(@RequestParam String filePath) {
        File file = new File(localPathDir + filePath);
        if (!file.exists() || !file.isFile()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Resource resource = new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .body(resource);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("/upload")
    public FileVo returnImg(@RequestBody MultipartFile file) throws IOException {
        return fileService.upload(file);
    }
}